package com.example.gyk_search

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.RecyclerView
import com.example.gyk_search.MyApplication.Companion.context


/**
 * Created by DomenCai on 2022/1/20.
 */
class ContactAdapter: RecyclerView.Adapter<ContactAdapter.ContactViewHolder>() {
 private val contactList: MutableList<ContactInfo> = mutableListOf()

 @SuppressLint("NotifyDataSetChanged")
 fun updateList(newList: List<ContactInfo>) {
  contactList.clear()
  contactList.addAll(newList)
  notifyDataSetChanged()
 }

 inner class ContactViewHolder(view: View) : RecyclerView.ViewHolder(view) {
  val contactName: TextView = view.findViewById(R.id.contactname)
  val contactNum: TextView = view.findViewById(R.id.contactnum)
 }

 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactViewHolder {
  val view = LayoutInflater.from(parent.context)
   .inflate(R.layout.contactinfo_item, parent, false)
  val viewHolder = ContactViewHolder(view)

  viewHolder.contactNum.setOnClickListener{
   val position = viewHolder.adapterPosition
   val contactNumInfo = contactList[position].contactNum
   val intent = Intent()
   intent.action = Intent.ACTION_DIAL//dial是拨号的意思
   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)//什么时候用
   intent.data = Uri.parse("tel:"+ contactNumInfo)//这个tel不能改，后面的数字可以随便改
   startActivity(context,intent,null)
  }

  viewHolder.contactName.setOnClickListener{
   val position = viewHolder.adapterPosition
   val contactNumInfo = contactList[position].contactNum
   val intent = Intent()
   intent.action = Intent.ACTION_DIAL//dial是拨号的意思
   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)//什么时候用
   intent.data = Uri.parse("tel:"+ contactNumInfo)//这个tel不能改，后面的数字可以随便改
   startActivity(context,intent,null)
  }

  //跳转到联系人详细界面

  return viewHolder
 }

 override fun onBindViewHolder(holder: ContactAdapter.ContactViewHolder, position: Int) {
  val contactInfo = contactList[position]
  holder.contactName.text=contactInfo.contactName
  holder.contactNum.text = contactInfo.contactNum
 }

 override fun getItemCount() = contactList.size
}